
#include "LuaNet.h"

namespace LuaGui {
#if defined(USE_LIBUV)
	static uint64_t StartServer(std::string ip = "0.0.0.0", unsigned int port = 80) {
		TcpServer* server = new TcpServer();

		int ret = server->Start(ip, port);

		if (ret != 0)
		{
			delete server;
			return 0;
		}

		return server->GetUID();
	}

	static void StopServer(uint64_t serverUID) {
		TcpServer* server = TcpServer::GetTcpServerByUID(serverUID);
		if (!server) return;
		server->Stop();
	}

	static uint64_t ConnectServer(std::string ip = "0.0.0.0", unsigned int port = 80) {
		return TcpSocket::Connect(ip, port)->GetUID();
	}

	static void SendTcpSocketData(uint64_t socketUID, std::string data) {
		TcpSocket* socket = TcpSocket::GetTcpSocketByUID(socketUID);
		if (!socket) return;
		socket->Send(data);
	}

	static void CloseTcpSocket(uint64_t socketUID) {
		TcpSocket* socket = TcpSocket::GetTcpSocketByUID(socketUID);
		if (!socket) return;
		socket->Close();
	}

	void LuaNet::Register(lua_State* L) {
		luabridge::getGlobalNamespace(L)
			.beginNamespace("LuaGui")
			.addFunction("StartServer", StartServer)
			.addFunction("StopServer", StopServer)
			.addFunction("ConnectServer", ConnectServer)
			.addFunction("SendTcpSocketData", SendTcpSocketData)
			.addFunction("CloseTcpSocket", CloseTcpSocket)
			.endNamespace();
	}
#else

	void LuaNet::Register(lua_State* L) {

	}
#endif
}
